import { Component, Injector, OnInit, ViewChild } from '@angular/core';
import { FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms';
import { STColumn, STData } from '@delon/abc/st';
import { SFSchema, SFUISchema } from '@delon/form';
import { FunctionViewComponent } from '@shared/components/function-view/function-view.component';
import { ModalTreeComponent } from '@shared/components/modal-tree/modal-tree.component';
import { STComponentBase } from '@shared/itcore/components/st-component-base';
import { FilterGroup } from '@shared/itcore/itcore.model';
import { ItcoreSTColumn } from '@shared/itcore/services/alain.types';
import { NzMessageService } from 'ng-zorro-antd/message';
import { NzTreeNode } from 'ng-zorro-antd/tree';
import { UploadFile } from 'ng-zorro-antd/upload';

@Component({
  selector: 'app-user',
  templateUrl: './user.component.html',
  styles: [],
})
export class UserComponent extends STComponentBase implements OnInit {
  constructor(injector: Injector, private fb: FormBuilder, private message: NzMessageService) {
    super(injector);
    this.moduleName = 'user';
  }

  /** 是否展现重置密码弹窗 */
  public isVisibleResetModal = false;
  //#region 重置密码 方法
  private currentOperateData: STData;
  validateResetForm: FormGroup;
  //#endregion

  // #region 角色设置

  roleTitle: string;
  roleTreeDataUrl: string;
  @ViewChild('roleModal', { static: false }) roleModal: ModalTreeComponent;

  // #endregion

  // #region 权限设置

  moduleTitle: string;
  moduleTreeDataUrl: string;
  @ViewChild('moduleModal', { static: false }) moduleModal: ModalTreeComponent;

  // #endregion

  // #region 查看功能

  functionTitle: string;
  functionVisible = false;
  functionReadUrl: string;
  @ViewChild('function', { static: false }) function: FunctionViewComponent;

  ngOnInit() {
    super.InitBase();

    this.validateResetForm = this.fb.group({
      NewPassword: [null, [Validators.required]],
      ConfirmPassword: [null, [Validators.required]],
    });
  }

  protected GetSTColumns(): ItcoreSTColumn[] {
    return [
      {
        title: '操作',
        fixed: 'left',
        width: 65,
        buttons: [
          {
            text: '操作',
            children: [
              {
                text: '编辑',
                icon: 'edit',
                acl: 'Root.Admin.Identity.User.Update',
                iif: (row) => row.Updatable,
                click: (row) => this.edit(row),
              },
              { text: '角色', icon: 'team', acl: 'Root.Admin.Identity.User.SetRoles', click: (row) => this.roles(row) },
              // {
              //   text: '权限',
              //   icon: 'safety',
              //   acl: 'Root.Admin.Identity.User.SetModules',
              //   click: row => this.module(row),
              // },
              {
                text: '删除',
                icon: 'delete',
                type: 'del',
                acl: 'Root.Admin.Identity.User.Delete',
                iif: (row) => row.Deletable,
                click: (row) => this.delete(row),
              },
              {
                text: '重置密码',
                icon: 'reload',
                acl: 'Root.Admin.Identity.User.ResetPassword',
                click: (row) => this.resetPassword(row),
              },
              {
                text: '查看功能',
                icon: 'security-scan',
                acl: 'Root.Admin.Auth.UserFunction',
                click: (row) => this.viewFunction(row),
              },
            ],
          },
        ],
        required: ['UserName', 'NickName', 'Email', 'PhoneNumber', 'Password'],
      },
      { title: '编号', index: 'Id', sort: true, readOnly: true, editable: true, type: 'number', filterable: true },
      {
        title: '用户名',
        index: 'UserName',
        sort: true,
        editable: true,
        ftype: 'string',
        filterable: true,
        minLength: 3,

        // ui: {
        //   widget: 'tinymce',

        // }
      },
      {
        title: '昵称',
        index: 'NickName',
        sort: true,
        editable: true,
        ftype: 'string',
        filterable: true,
      },
      { title: '邮箱', index: 'Email', sort: true, editable: true, ftype: 'string', filterable: true, fformat: 'email' },
      {
        title: '手机号',
        index: 'PhoneNumber',
        sort: true,
        editable: true,
        ftype: 'string',
        filterable: true,
        fformat: 'mobile',
        ui: {
          errors: {
            format: '手机号格式不正确',
          },
        },
      },
      // { title: '邮箱确认', index: 'EmailConfirmed', sort: true, type: 'yn', editable: true, filterable: true },
      // { title: '手机确认', index: 'PhoneNumberConfirmed', sort: true, type: 'yn', editable: true, filterable: true },
      { title: '角色', index: 'Roles', format: (d) => this.itcore.expandAndToString(d.Roles) },
      { title: '是否锁定', index: 'IsLocked', sort: true, type: 'yn', editable: true, filterable: true },
      // { title: '登录锁', index: 'LockoutEnabled', sort: true, type: 'yn', editable: true, filterable: true },
      { title: '登录错误', index: 'AccessFailedCount', sort: true, editable: false, ftype: 'number', filterable: true },
      // { title: '锁时间', index: 'LockoutEnd', sort: true, editable: true, type: 'date', filterable: true },
      { title: '注册时间', index: 'CreatedTime', sort: true, type: 'date', filterable: true },
    ];
  }

  protected GetExpandSFSchema(): ItcoreSTColumn[] {
    return [
      {
        title: '登录密码',
        index: 'Password',
        ftype: 'string',
        editable: true,
        IsHideEdit: true,
        minLength: 6,
        description: `密码至少是6个字符，密码至少有一个小写字母 ('a'-'z')`,
      },
    ];
  }

  protected GetSFUISchema(): SFUISchema {
    const ui: SFUISchema = {
      '*': { spanLabelFixed: 100, grid: { span: 12 } },
      $UserName: { grid: { span: 20 } },
      $NickName: { grid: { span: 20 } },
      $Email: { grid: { span: 20 } },
      $PhoneNumber: { grid: { span: 20 } },
      $LockoutEnd: { grid: { span: 20 } },
      $Password: { grid: { span: 20 } },
    };
    return ui;
  }

  resetPassword(value: STData) {
    this.currentOperateData = value;
    this.isVisibleResetModal = true;
  }
  // 取消
  handleCancelResetModal(): void {
    this.isVisibleResetModal = false;
    this.validateResetForm.reset();
  }
  // 确认
  resetPasswordConfirm(): void {
    // tslint:disable-next-line: forin
    for (const i in this.validateResetForm.controls) {
      this.validateResetForm.controls[i].markAsDirty();
      this.validateResetForm.controls[i].updateValueAndValidity();
    }

    if (this.validateResetForm.value.NewPassword !== this.validateResetForm.value.ConfirmPassword) {
      this.message.create('error', '两次密码不一致！');
      return;
    }
    if (this.validateResetForm.valid) {
      this.validateResetForm.value.UserId = this.currentOperateData.Id;
      this.validateResetForm.value.Token = '';
      this.http.post('api/Admin/User/ResetPassword', [this.validateResetForm.value]).subscribe((result) => {
        this.itcore.ajaxResult(result, () => {
          this.currentOperateData = null;
          this.isVisibleResetModal = false;
          this.validateResetForm.reset();
        });
      });
    }
  }

  private roles(row: STData) {
    this.editRow = row;
    this.roleTitle = `设置用户角色 - ${row.UserName}`;
    this.roleTreeDataUrl = `api/admin/role/ReadUserRoles?userId=${row.Id}`;
    this.roleModal.open();
  }

  setRoles(value: NzTreeNode[]) {
    const ids = this.alain.GetNzTreeCheckedIds(value);
    const body = { userId: this.editRow.Id, roleIds: ids };
    this.http.post('api/admin/user/setRoles', body).subscribe((result) => {
      this.itcore.ajaxResult(result, () => {
        this.st.reload();
        this.roleModal.close();
      });
    });
  }

  private module(row: STData) {
    this.editRow = row;
    this.moduleTitle = `设置用户权限 - ${row.UserName}`;
    this.moduleTreeDataUrl = `api/admin/module/ReadUserModules?userId=${row.Id}`;
    this.moduleModal.open();
  }

  setModules(value: NzTreeNode[]) {
    const ids = this.alain.GetNzTreeCheckedIds(value);
    const body = { userId: this.editRow.Id, moduleIds: ids };
    this.http.post('api/admin/user/setModules', body).subscribe((result) => {
      this.itcore.ajaxResult(result, () => {
        this.st.reload();
        this.moduleModal.close();
      });
    });
  }

  private viewFunction(row: STData) {
    this.functionTitle = `查看用户功能 - ${row.Id}. ${row.UserName}`;
    this.functionVisible = true;

    this.functionReadUrl = `api/admin/userfunction/readfunctions?userId=${row.Id}`;
    const filter: FilterGroup = new FilterGroup();
    setTimeout(() => {
      this.function.reload(filter);
    }, 100);
  }

  closeFunction() {
    this.functionVisible = false;
  }
  // #endregion
}
